@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

:: Use absolute paths for reliability
set "WORKSPACE=%~dp0.."
set "LUBAN_DLL=%WORKSPACE%\Tools\Luban\Luban.dll"
set "CONF_ROOT=%~dp0"

:: Debug info
echo [DEBUG] Current directory: %cd%
echo [DEBUG] WORKSPACE: "%WORKSPACE%"
echo [DEBUG] LUBAN_DLL: "%LUBAN_DLL%"
echo [DEBUG] CONF_ROOT: "%CONF_ROOT%"

:: Verify critical files
if not exist "%LUBAN_DLL%" (
    echo [ERROR] Luban.dll not found at "%LUBAN_DLL%"
    exit /b 1
)

if not exist "%CONF_ROOT%luban.conf" (
    echo [ERROR] luban.conf not found at "%CONF_ROOT%luban.conf"
    exit /b 1
)

:: Prepare output directories
if not exist "output" mkdir %CONF_ROOT%output
if not exist "output\GenCode" mkdir %CONF_ROOT%output\GenCode

:: Build arguments
set "EXTRA_ARGS="
for %%a in (%*) do (
    set "EXTRA_ARGS=!EXTRA_ARGS! -c %%a"
    set "EXTRA_ARGS=!EXTRA_ARGS! -x %%a.outputCodeDir=%CONF_ROOT%output/GenCode/%%a"
)

echo Executing Luban with arguments: %EXTRA_ARGS%

:: Execute Luban with real-time output AND logging
(
    echo ===== LUBAN OUTPUT START =====
    dotnet "%LUBAN_DLL%" ^
        -t all ^
        --conf "%CONF_ROOT%luban.conf" ^
        -d protobuf3-bin ^
        -x protobuf3-bin.outputDataDir=%CONF_ROOT%output/data/protobuf3-bin ^
        -d json ^
        -x json.outputDataDir=%CONF_ROOT%output/data/json ^
        %EXTRA_ARGS%
    echo ===== LUBAN OUTPUT END =====
) > %CONF_ROOT%luban_output.log 2>&1

:: Display Luban output in console
type %CONF_ROOT%luban_output.log

:: Check exit code
set "exitCode=%errorlevel%"
if %exitCode% neq 0 (
    echo [ERROR] Luban failed with code: %exitCode%
    if %exitCode% EQU 3 (
        echo Common causes for error 3:
        echo 1. Invalid configuration
        echo 2. Data validation failed
        echo 3. Missing template files
    )
    exit /b %exitCode%
)

echo [SUCCESS] Operation completed
exit /b 0